// packageA/pages/trainReportDetail/trainReportDetail.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');

//画布相关
var context = null;
var isButtonDown = false;
var arrx = [];
var arry = [];
var arrz = [];
var canvasw = 0;
var canvash = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //信息
    editInfo:{},
    //签名默认值
    sign:{
      learned: true,
      trainScore: 5
    },
    //培训内容
    contentDictionary:[],
    //培训提示
    tipsDictionary:[],
    //培训注意事项
    notesDictionary:[],
    //人员选择框
    showStaff:false,
    //人员选择数据
    staffList:[], 
    //选择的人员
    trainingStaff:null,
    //培训方式选择框
    showType:false,
    //培训方式选择数据
    typeList:[{
      id:1,
      text:'线上培训'
    },{
      id:2,
      text:'线下培训'
    }],   
    //签名弹出层
    showSign:false,  
    //登录用户type
    userType:null,
    //登录用户
    user:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user = app.globalData.userInfo;
    this.setData({
      user: user,
      userType: user.departObj[0].type
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })
      
      //获取培训报告
      this.getInfo();

      //获取培训内容
      this.getContent();

      //获取提示
      this.getTips();
      
      //获取注意事项
      this.getNotes();
      
      //准备画布
      this.canvasInit();
    }  
  },

  //获取培训报告
  getInfo(){
    let param = {
      isAuth: false,
      className: 'trainingReport',
      data: {
        id: this.data.paramObj.id,
        selectFields: ['id','trainNo','order','trainingStaff','state','sign','oldTrainers','trainType','options']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('培训报告回显');
        console.log(result);
        
        //签名默认值
        if(result.state==0){
          result.sign=this.data.sign;
        }

        //处理工作开始时间
        if(result.order.openWorkData){
          result.order.openWorkData=util.timeFormat(result.order.openWorkData);
        }

        this.setData({
          editInfo: result,
          trainingStaff: result.trainingStaff
        })
      }
    }).catch((error) => {
    })
  },

  //提交信息
  onConfirm(){
    let td=this.data;
    let editInfo=td.editInfo;
    let _this=this;

    //验证签名非空
    if(!editInfo.sign.signImg){
      Toast.fail('请签名');
      return;
    }

    //验证手机号
    if(editInfo.sign.signPhone!=null){
      let phone=editInfo.sign.signPhone.trim();
      if(phone){
        if(!util.checkPhoneFormat(phone)){
          Toast.fail('手机号格式错误');
          return;
        }
      }else{
        Toast.fail('请输入手机号');
        return;
      }
    }else{
      Toast.fail('请输入手机号');
      return;
    }  

    //上传图片
    wx.uploadFile({
      url: app.globalData.ossUrl + 'headImgUpload?filepath=zhandouli/electronicSign/',
      filePath: editInfo.sign.signImg,
      name: 'file',
      success(res) {
        let imgUrl = JSON.parse(res.data).data;                  
        if(imgUrl.indexOf("?")!=-1){
          let index = imgUrl.indexOf("?");
          if (index != -1) {
            imgUrl = imgUrl.substring(0, index); 
          }
        }

        let sign={
          //勾选
          learned: editInfo.sign.learned,
          //评分
          trainScore: editInfo.sign.trainScore,
          //签名
          signImg: imgUrl,
          //手机号
          signPhone: editInfo.sign.signPhone,
          //签名日期
          signTime: util.timeFormat(new Date())
        }
        
        //提交表单
        let param={
          className:'trainingReport',
          data:{
            id: editInfo.id,
            sign: sign,
            state: 1
          }
        }

        // console.log('~提交~');
        // console.log(param);

        CommonService.goSave(param).then(res=>{
          if (res.statusCode == 200 && res.data.success == true){
            Toast.success('成功');

            //更新设备租赁时间
            _this.updateLeaseTime(sign.signTime);

            setTimeout(() => {
              //返回列表页并刷新数据
              _this.backAndRefresh();
            }, 1000);
          }else if(res.statusCode==202){
            Toast.fail('您操作太快了,请勿重复提交');
          }else{
            Toast.fail('操作失败');
          }
        }).catch((error) => {
          Toast.fail('操作失败');
        })

      }, 
      fail(){
        Toast('签名上传失败');               
      }              
    });
  },

  //获取培训内容
  getContent(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'trainingContent',
        category:this.data.paramObj.categoryId,
        selectFields: ['content']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        this.setData({
          contentDictionary: result
        })
      }
    }).catch((error) => {
    })
  },

  //获取提示
  getTips(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'trainingContentTips',
        selectFields: ['content']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        this.setData({
          tipsDictionary: result
        })
      }
    }).catch((error) => {
    })
  },
  
  //获取注意事项
  getNotes(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'trainingNotes',
        selectFields: ['content']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        this.setData({
          notesDictionary: result
        })
      }
    }).catch((error) => {
    })
  },

  //勾选是否熟悉
  onChangeChecke(event) {
    let learned='editInfo.sign.learned';
    this.setData({
      [learned]: event.detail
    })
  },

  //星星评分
  onChangeStar(event) {
    let trainScore='editInfo.sign.trainScore';
    this.setData({
      [trainScore]: event.detail
    })
  },

  //电话
  onGetPhone(e){
    let signPhone='editInfo.sign.signPhone';
    this.setData({
      [signPhone]: e.detail.value
    })
  },

  //显示签名
  onShowSign(){
    this.setData({
			showSign: true
    })
  },

  //隐藏签名
  onCloseSign(){
    this.setData({
      showSign: false
    })
  },  

  //画布
  canvasInit(){
    wx.createSelectorQuery()
      .select("#canvas")
      .context(function (res) {
        context = res.context;
      }).exec();

    var _this = this;
    
    //获取系统信息
    wx.getSystemInfo({
      success(res){
        canvasw = res.windowWidth;
        canvash = res.windowHeight;
        _this.setData({ 
          canvasw: canvasw,
          canvash: canvash
        })
      }
    });

    //清除画布
    this.cleardraw();
  },

  //绘制开始
  canvasStart(event){
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
  },

  //绘制过程
  canvasMove(event){
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    };

    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      };
    };
    context.clearRect(0, 0, canvasw, canvash);

    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();

    context.draw(false);
  },

  //绘制结束
  canvasEnd(event){
    isButtonDown = false;
  },

  //清除画布
  cleardraw(){    
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  },

  //确认签名
  onConfirmSign(){
    let _this=this;
    if(arrx.length){
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        success: function (res) {
          let signImg='editInfo.sign.signImg';
          _this.setData({
            [signImg]: res.tempFilePath
          })  
          
          _this.onCloseSign();
        }
      })
    }else{
      Toast.fail('签名内容不能为空');
    }
  },

  //显示培训人员
  onShowStaff(){
    this.setData({
			showStaff: true
    })
    this.getStaffList();
  },

  //查询培训人员
  getStaffList(){
    this.setData({
      staffList: []
    })

    let param={
      isAuth:true,
      className:'servicePersonal',
      data:{
        searchAll:true,  
        selectFields: ['id','serviceName','telephone','type'],
        sort: {
          id: -1
        },
      }
    }

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        param.data.appId=app.globalData.myAppId;
      }else{
        param.data.appId=[2,3,null];
      }
    }else{
      param.data.appId=[2,3,null];
    }

    //模糊查询
    if(this.data.valueSearchStaff){
      param.data.serviceName='%'+this.data.valueSearchStaff+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].serviceName,
            id:list[i].id,
            obj:list[i]
          }
          arr.push(obj);
        }
        this.setData({
          staffList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏培训人员
  onCloseStaff(){
    this.setData({
      showStaff: false,
      valueSearchStaff:''
    })
  },

  //确认培训人员
  onConfirmStaff(e){
    let obj=e.detail.value.obj;
    this.setData({
      trainingStaff:{
        id: obj.id,
        name: obj.serviceName,
        phone: obj.telephone,
        type: obj.type
      }
    })
    this.onCloseStaff();
  },

  //搜索培训人员
  onChangeStaff(e){
    this.setData({
      valueSearchStaff: e.detail
    })
    this.getStaffList();
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.getList();
    wx.navigateBack();
  },

  //显示培训方式
  onShowType(){
    this.setData({
			showType: true
    })
  },

  //隐藏培训方式
  onCloseType(){
    this.setData({
      showType: false
    })
  },

  //确认培训方式
  onConfirmType(e){
    let trainType='editInfo.trainType';
    this.setData({
      [trainType]:e.detail.value.id
    })

    this.onCloseType();
  },

  //修改的数据提交
  onSaveStaff(){
    let editInfo=this.data.editInfo;
    let staff=editInfo.trainingStaff;
    let newStaff=this.data.trainingStaff;  
    let options=editInfo.options;

    //修改过的人员
    let oldTrainers=[];
    if(editInfo.oldTrainers && editInfo.oldTrainers.length){
      oldTrainers=editInfo.oldTrainers;
    }

    if(newStaff.id!=staff.id){
      staff.changeTime=util.timeFormat(new Date());
      oldTrainers.push(staff);
      //工单记录
      options.push({
        content: this.data.user.userName + ' 更换培训人员为：' + newStaff.name,
        timestamp: util.timeFormat(new Date())
      });
    }
    
    let param={
      className:'trainingReport',
      data:{
        id: editInfo.id,
        trainingStaff: newStaff,
        oldTrainers: oldTrainers,
        trainType: editInfo.trainType,
        options: options
      }
    }

    //console.log(param.data);
  
    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('已修改');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000); 
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })    
  },

  //更新设备租赁时间
  updateLeaseTime(time){ 
    let obj=this.data.editInfo.order;
 
    let param={
      orderDetailId: obj.orderDetailId,
      orderDetailInedx: obj.orderDetailInedx,
      orderNo: obj.orderNo,
      signTime: time
    }
    
    CommonService.updateLeaseTime(param).then(res=>{
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})